<template>
    <div class="person-setting">
      <header class="header">
        <div class="header-box">
        </div>
      </header>
      <Row justify="center" type="flex" class-name="main-box">
        <i-col :span="19">
          <div class="form-box">
            <div class="form-header">
              <div class="form-header-left">
                <Avatar style="width: 1.22rem;height: 1.22rem" :src="avatarImg"></Avatar>
                <BaseUpload
                  name="file"
                  btn-type="text"
                  :showUploadList="false"
                  btn-icon=""
                  class="base-upload"
                  btn-text="更改头像"
                  @publicSuccess="handleSuccess"
                  :action="action.upload"
                  :headers="{authToken}"
                />
               <!-- <a class="update-avatar" @click.prevent="updateAvatar">修改头像</a> -->
              </div>
              <div class="form-header-right">
                <h3 class="user-name">{{userInfo.userName}}</h3>
                <p class="user-account">账号：{{userInfo.userAccount}}</p>
                <p class="register-time">注册时间：{{userInfo.createTime}}</p>
                <p class="last-login">最后登录：{{userInfo.lastLoginTime}}</p>
              </div>
            </div>
            <div class="Immutable">
              <p class="dept-account">
                <span class="account">
                  <Tooltip key="dept-account-yes-key" :content="userInfo.userInfo.rfPositionDictName" placement="top" v-if="userInfo.userInfo.rfPositionDictName">
                     职位&nbsp;&nbsp;&nbsp;&nbsp;：{{userInfo.userInfo.rfPositionDictName || '暂无'}}
                  </Tooltip>
                  <template v-else>
                    <span key="dept-account-no-key">职位&nbsp;&nbsp;&nbsp;&nbsp;：{{(userInfo.userInfo || {}).rfPositionDictName || '暂无'}}</span>
                  </template>
                </span>
                <span class="dept">
                  <Tooltip key="dept-account-dept-yes-key" :content="deptStr" placement="top" v-if="this.userInfo.deptList && this.userInfo.deptList.length > 0">
                     部&nbsp;&nbsp;&nbsp;&nbsp;门：{{deptStr}}
                  </Tooltip>
                  <template v-else>
                    <span key="dept-account-dept-mo-key" >暂无</span>
                  </template>
                </span>
              </p>
              <p class="name-role">
                <!-- | splitFilters(3) -->
                <!-- <span class="name">用户名：{{userInfo.userName}}</span> -->
                <span class="role">所属角色：
                  <template v-if="userInfo.roleList.length > 0">
                     <span>{{roleStr}}
                  </span>
                  </template>
                   <template v-else>
                    暂无
                  </template>
                </span>
              </p>
            </div>
            <Form
              label-colon
              :label-width="65"
              ref="formValidate"
              :show-message="false"
              :rules="ruleValidate"
              :model="userInfo"
              label-position="left"
            >
              <FormItem :label-width="110">
                <template slot="label">
                  第三方认证：
                </template>
                <p>
                  <Button
                   style="margin-right: 10px;"
                   @click="handleBindDingTalk(isBindDingTalk)" :type="isBindDingTalk ? 'primary' : 'default'">{{ isBindDingTalk ? '解绑钉钉' : '绑定钉钉' }}</Button>
                  <Button style="margin-right: 10px;">绑定QQ</Button>
                  <Button style="margin-right: 10px;">绑定微信</Button>
                </p>
              </FormItem>
              <FormItem prop="userInfo.email">
                <template slot="label">
                  邮&nbsp;&nbsp;&nbsp;&nbsp;箱：
                </template>
                <i-input v-model="userInfo.userInfo.email"></i-input>
              </FormItem>
              <FormItem label="微信号">
                <i-input v-model="userInfo.userInfo.wechat"></i-input>
              </FormItem>
              <FormItem label="QQ号">
                <i-input v-model="userInfo.userInfo.qq"></i-input>
              </FormItem>
              <FormItem label="手机号" prop="userInfo.phone">
                <i-input v-model="userInfo.userInfo.phone"></i-input>
              </FormItem>
              <FormItem label="身份证" prop="userInfo.idCard">
                <i-input v-model="userInfo.userInfo.idCard"></i-input>
              </FormItem>
              <FormItem>
                <template slot="label">
                  性&nbsp;&nbsp;&nbsp;&nbsp;别:
                </template>
                <RadioGroup v-model="userInfo.userInfo.sex">
                  <Radio :label="0">男</Radio>
                  <Radio :label="1">女</Radio>
                  <Radio :label="2">保密</Radio>
                </RadioGroup>
              </FormItem>
              <FormItem>
                <template slot="label">
                  密&nbsp;&nbsp;&nbsp;&nbsp;码:
                </template>
                ******
                <Button type="primary" ghost style="margin-left: .3rem;font-size: 12px;height: auto" @click="updatePsw">修改</Button>
              </FormItem>

              <FormItem style="margin-top: .39rem;margin-bottom: .64rem;" class="btn-form" :label-width="0">
                <Button type="primary" @click="handleSubmit('formValidate')">立即提交</Button>
                <Button type="error" style="margin-left: .6rem" @click="handleEdit">返回</Button>
              </FormItem>
            </Form>
          </div>
        </i-col>
      </Row>
      <Drawer
        :draggable="true"
        v-model="viewParams.flag"
        :width="30"
        title="修改密码">
        <Form
          ref="pswForm"
          label-colon
          :rules="pswRules"
          :model="pswModel"
          :label-width="80">
          <FormItem prop="oldPass">
            <template slot="label">
              旧密码
            </template>
            <i-input v-model="pswModel.oldPass" :password="true" type="password"></i-input>
          </FormItem>
          <FormItem prop="newPass">
            <template slot="label">
              新密码
            </template>
            <i-input v-model="pswModel.newPass" :password="true" type="password"></i-input>
          </FormItem>
          <FormItem prop="pswCheck">
            <template slot="label">
              确定密码
            </template>
            <i-input v-model="pswModel.pswCheck" :password="true" type="password"></i-input>
          </FormItem>
          <FormItem style="text-align: center;margin-top: .39rem;" class="btn-form">
            <Button type="primary" @click="handleUpdatePsw('pswForm')">确定</Button>
            <Button type="error" style="margin-left: .3rem" @click="cancelUpdatePsw('pswForm')">取消</Button>
          </FormItem>
        </Form>
      </Drawer>
      <Modal v-model="isShowDingTalk" width="365" :footer-hide="true">
        <div id="login_container">
        </div>
      </Modal>
    </div>
</template>

<script>
import {
  getPersonInformationUser,
  updateLoginUser,
  updateMyPass
} from '../../api/modules/person/person'
import { typeOf } from '../../utils/verification'
import API_KEY from '../../api/index'
import message from '../../utils/message'
import { loginOut, unBindDingTalk, getDingTalkAuthentication, bindDingTalk } from '../../api/modules/login/login'
import { goLogin } from '../../router'
import { mapMutations, mapGetters } from 'vuex'
import BaseUtil from '../../utils/BaseUtil'
import { openDingTalkQrCode } from '../../api/modules/login/thirdParty'
export default {
  name: 'personSetting',
  data () {
    // 自定义手机号校验规则
    const validatePhone = (rule, value, callback) => {
      const reg = /^1(3|4|5|6|7|8|9)\d{9}$/
      if (value !== '' && !reg.test(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    // 自定义身份证校验规则
    const validateIDCard = (rule, value, callback) => {
      const reg = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/
      if (value !== '' && !reg.test(value)) {
        callback(new Error('身份证格式错误'))
      } else {
        callback()
      }
    }
    const checkPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('密码不能为空'))
      } else {
        if (this.pswModel.pswCheck !== '') {
          this.$refs.pswForm.validateField('pswCheck')
        }
        callback()
      }
    }
    const checkSurePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.pswModel.newPass) {
        callback(new Error('两次密码不一致，请检查后重新输入'))
      } else {
        callback()
      }
    }
    return {
      userInfo: {
        userName: '超级用户',
        userAccount: '超级用户',
        createTime: '2019-09-30 11:33:22',
        lastLoginTime: '2019-09-30 11:33:22',
        deptList: [],
        roleList: [],
        thirdPartyAccountList: [],
        userInfo: {
          wechat: '',
          email: '',
          phone: '',
          idCard: '',
          headPath: '',
          rfPositionDictName: '',
          qq: '',
          sex: 0
        },
        version: 0,
        uploadPath: ''
      },
      action: {
        upload: API_KEY.fileLog.createFileLog
      },
      ruleValidate: {
        'userInfo.email': [{ message: '请输入正确的邮箱地址', type: 'email', trigger: 'change' }],
        'userInfo.phone': [{ validator: validatePhone, trigger: 'change' }],
        'userInfo.idCard': [{ validator: validateIDCard, trigger: 'change' }]
      },
      viewParams: {
        flag: false
      },
      pswRules: {
        oldPass: [{ required: true, message: '请输入旧密码', trigger: 'change' }],
        newPass: [{ min: 6, message: '密码不能少于6位数', trigger: 'change' },
          { validator: checkPassword, trigger: 'change' }],
        pswCheck: [{ validator: checkSurePassword, trigger: 'change' }]
      },
      pswModel: {
        oldPass: '',
        newPass: '',
        pswCheck: ''
      },
      dingding: '',
      qq: '',
      isShowDingTalk: false,
      isUnBind: false,
      nailedFormValidate: {
        code: '',
        state: ''
      }
    }
  },
  created () {
    this.privateInit()
  },
  filters: {
    splitFilters (val, max) {
      if (val.length > max) {
        return val.substr(0, max) + '...'
      }
      return val
    }
  },
  computed: {
    avatarImg () {
      if (this.userInfo.userInfo.headPath) {
        return BaseUtil.getUploadPath(this.userInfo.userInfo.headPath)
      } else {
        return require('@/assets/imgs/home/header.png')
      }
    },
    currRouter () {
      return this.$route.path
    },
    roleStr () {
      let str = ''
      const role = this.userInfo.roleList || []
      role.forEach(item => {
        str += item.roleName + ','
      })
      return str.substring(0, str.length - 1)
    },
    deptStr () {
      let str = ''
      const dept = this.userInfo.deptList || []
      dept.forEach(item => {
        str += item.deptName + ','
      })
      return str.substring(0, str.length - 1)
    },
    isBindDingTalk () {
      const thirdPartyAccountList = this.userInfo.thirdPartyAccountList || []
      return thirdPartyAccountList.some(item => item.appType === 'dingTalk')
    },
    ...mapGetters(['authToken'])
  },
  watch: {
    $route: {
      immediate: true,
      handler (val) {
        // 钉钉扫码登录
        if (val.params.type && val.params.type === 'dingTalk') {
          const query = val.query
          const { code, state } = query
          if (code && state) {
            this.nailedFormValidate.code = code
            this.nailedFormValidate.state = state
            bindDingTalk(this.nailedFormValidate).then(data => {
              message.message.success(data.message)
              this.$router.replace('/personSetting')
              this.getUserInfo()
            })
          }
        }
      }
    }
  },
  components: {
    BaseUpload: () => import('@/components/view-ui/BaseUpload')
  },
  methods: {
    ...mapMutations({
      updateHeader: 'UPDATE_HEADER'
    }),
    /**
     * 可看着是当前组件初始
     */
    privateInit () {
      this.getUserInfo()
    },
    /**
     * 获取用户信息
     */
    getUserInfo () {
      getPersonInformationUser().then(({ data }) => {
        //  改换缓存中存储的头部信息
        this.updateHeader(data.userInfo.headPath ? data.userInfo.headPath : '')
        Object.keys(this.userInfo).forEach((item) => {
          if (typeOf(this.userInfo[item]) === 'object') {
            Object.keys(this.userInfo[item]).forEach((item1) => {
              if (typeOf(data[item][item1]) !== 'undefined') {
                this.$set(this.userInfo[item], item1, data[item][item1])
              }
            })
          } else {
            if (typeOf(data[item]) !== 'undefined') {
              this.$set(this.userInfo, item, data[item])
            }
          }
        })
      })
    },
    /**
     * 头像上传成功后触发
     */
    handleSuccess (res) {
      const { response } = res
      // 更换当前用户头像
      this.$set(this.userInfo.userInfo, 'headPath', response.data.uploadPath)
      this.userInfo.userInfo.fkHeadId = response.data.id
    },
    /**
     * 提交
     * @param name
     */
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          updateLoginUser(this.userInfo.userInfo).then((data) => {
            message.message.success(data.message)
            // 更新用户信息
            this.getUserInfo()
          })
        } else {
          message.message.error('输入数据格式有误，请检查后重试')
        }
      })
    },
    /**
     * 退出到个人中心
     */
    handleEdit: function () {
      if (this.currRouter !== '/personCenter') {
        this.$router.push({ path: '/personCenter' })
      }
    },
    /**
     * 更改密码
     */
    updatePsw () {
      // 重置密码表单
      this.$refs.pswForm.resetFields()
      this.viewParams.flag = true
    },
    /**
     * 修改密码
     */
    handleUpdatePsw (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          message.modal.confirm('修改操作', '你确定要修改密码吗？', () => {
            const params = {
              oldPass: this.pswModel.oldPass,
              newPass: this.pswModel.newPass
            }
            updateMyPass(params).then((data) => {
              message.modal.success(data.message, '即将为你跳转到登录页面', () => {
              // 请求登出
                loginOut().then(data => {
                // 跳转到登录页
                  goLogin()
                })
              })
            })
          })
        } else {
          message.message.error('输入数据格式有误，请检查后重试')
        }
      })
    },
    /**
     * 取消密码修改
     * @param name
     */
    cancelUpdatePsw (name) {
      if (name) {
        this.$refs[name].resetFields()
        this.viewParams.flag = false
      }
    },
    /**
     * 绑定钉钉账号
     */
    handleBindDingTalk (code) {
      if (code) {
        message.modal.confirm('解绑钉钉', '您确定要解绑该钉钉吗？', () => {
          // 钉钉解绑
          unBindDingTalk().then(res => {
            if (res.code === '0') {
              message.message.success(res.message)
              // 重新请求查询个人信息
              this.privateInit()
            }
          })
        }, () => {
          message.message.success('取消解绑钉钉成功')
        })
      } else {
        getDingTalkAuthentication().then(({ data }) => {
          const appId = data.appId || ''
          const callback = data.callback || ''
          // 获取钉钉登录并监听钉钉登录
          openDingTalkQrCode('dingTalk', callback, appId)
          // 打开对话框
          this.isShowDingTalk = true
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
  @import "../../assets/styles/scss/mixin";
.person-setting{
  width: 100%;
  height: 100%;
  .header{
    width: 100%;
    height: 3.9rem;
    overflow: hidden;
    .header-box{
      width: 100%;
      height: 4.5rem;
      margin-top: -60px;
      background: url('~@/assets/imgs/home/header.png') left top no-repeat;
      background-size: 100% auto;
    }
  }
  .main-box {
    .ivu-col {
      margin-top: -2.86rem;
      margin-bottom: .48rem;
      background: rgba(255, 255, 255, 1);
      box-shadow: 0px 6px 7px 0px rgba(32, 32, 32, 0.09);
      border-radius: 8px;
    }
    .form-box{
      width: 40%;
      margin: .65rem auto 0;
      .form-header{
        @include flexMixer(space-between, flex-start);
        .form-header-left{
          @include flexMixer(flex-start,center,column);
          .base-upload{
            margin-top: .1rem;
            /deep/.ivu-btn-text{
              span{
                color: #2B95FF;
              }
              &:focus{
                outline: 0;
                box-shadow: none;
              }
            }
          }
        }
        .form-header-right{
          margin-top: .19rem;
          font-size: 12px;
          color: #333333;
          .user-name{
            font-size: .2rem;
            margin-bottom: .14rem;
          }
        }
      }
      .Immutable{
        margin-top: .6rem;
        font-size: 16px;
        color: #333;
        .dept-account, .name-role{
          margin-bottom: 15px;
        }
        .ivu-tooltip{
          width: 100%;
        }
        /deep/ .ivu-tooltip-rel{
          width: 100%;
          overflow:hidden; /*超出部分隐藏*/
          white-space:nowrap; /*让文本强制在一行不换行*/
          text-overflow:ellipsis;
        }
        .dept-account{
          display: flex;
          justify-content: space-between;
          .account{
            flex: 1;
            width: 0;
            flex: 1;
            width: 0;
            overflow:hidden; /*超出部分隐藏*/
            white-space:nowrap; /*让文本强制在一行不换行*/
            text-overflow:ellipsis;
          }
          .dept{
            flex: 1;
            width: 0;
            overflow:hidden; /*超出部分隐藏*/
            white-space:nowrap; /*让文本强制在一行不换行*/
            text-overflow:ellipsis;
          }
        }
        // @include flexMixer(space-between, flex-start);
        // .dept-account, .name-role{
        //   @include flexMixer(flex-start, flex-start, column);
        // }
        // .dept, .role{
        //   margin: .3rem 0 .23rem 0;
        // }
      }
      .ivu-form-item{
        margin-bottom: .16rem;
      }
    }
  }
  /deep/ .ivu-form-item-label{
    font-size: 16px;
    color: #333;
  }
}
.btn-form{
  /deep/.ivu-form-item-content{
    margin-left: 0 !important;
  }
}
/deep/ .ivu-modal-body{
    padding: 0;
    overflow: hidden;
    height: 320px;
  }

</style>
